import path from 'path';
import fs from 'fs';
import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { findFileById, updateHouse } from '../house/house.service';
import { IMAGE_TYPE_GOODS, upload_imageName } from '../app/constants';
import { getGoods, getIdGoods, createShop, updateShop, deleteShop, shopStatusChange, getShopGoods, createFile, deleteFileById, byKeyWordSelect } from './goods.service';
import OSS from "ali-oss";

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status
  let postId = request.query.postId
  let pageNo = request.query.pageNo

  const data = await getGoods(parseInt(`${status}`, 10), parseInt(`${postId}`, 10), 10, parseInt(`${pageNo}`, 10));
  for (const item of data.data as any) {
    if ("image_id" in item && item.image_id > 0) {
      const imgData = await findFileById(item.image_id, 0, 0, 'medium')
      item.cover = imgData[0];
    }
  }

  response.send(data);
}

/**
 * 获取产品
 */
export const goods = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取产品 ID
  const { shop_id } = request.params;
  let pageNo = request.query.pageNo
  let status = request.query.status

  const data = await getShopGoods(parseInt(`${status}`, 10), parseInt(shop_id, 10), 10, parseInt(`${pageNo}`, 10));
  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const goodsDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdGoods(parseInt(postId, 10));
    let images = await findFileById(0, data.id, IMAGE_TYPE_GOODS, 'medium');
    data.images = images;

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 按关键词搜索（模糊查询）
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  let { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let goodsModel = request.body;

  /* 创建 */
  if (goodsModel.id && goodsModel.id > 0) {
    let image_id = goodsModel.image_id
    let img = await findFileById(image_id, 0, 0);
    if (!img || img.length === 0) {
      let imgs = await findFileById(0, goodsModel.id, 17);
      if (imgs && imgs.length > 0) {
        goodsModel.image_id = imgs[imgs.length - 1].id
      }
    }
    const data = await updateShop(goodsModel, parseInt(goodsModel.id, 10));
    response.send(data);
  } else {
    const data = await createShop(goodsModel);
    response.send(data);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取内容
  const post = _.pick(request.body, [
    'status',
    'name_zh',
    'name_ug',
    'price',
    'detail_zh',
    'detail_ug'
  ]);

  // 更新
  try {
    const data = await updateShop(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.params;

  // 删除
  try {
    const data = await deleteShop(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;


  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await shopStatusChange(parseInt(postId, 10), post);
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 初始化OSS客户端。请将以下参数替换为您自己的配置信息。
  const client = new OSS({
    region: 'oss-cn-beijing', // 示例：'oss-cn-hangzhou'，填写Bucket所在地域。
    accessKeyId: 'LTAI5tNGq1paq6keMtntM2CH', // 确保已设置环境变量OSS_ACCESS_KEY_ID。
    accessKeySecret: 'MenjKujH7u7wpfVZ6pJqM4O5a7JevP', // 确保已设置环境变量OSS_ACCESS_KEY_SECRET。
    bucket: 'qiyat', // 示例：'my-bucket-name'，填写存储空间名称。
  });

  // 自定义请求头
  const headers = {
    // 指定Object的存储类型。
    'x-oss-storage-class': 'Standard',
    // 指定Object的访问权限。
    'x-oss-object-acl': 'public-read',
    // 通过文件URL访问文件时，指定以附件形式下载文件，下载后的文件名称定义为example.txt。
    'Content-Disposition': 'attachment; filename="example.jpg"',
    // 设置Object的标签，可同时设置多个标签。
    'x-oss-tagging': 'Tag1=1&Tag2=2',
    // 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
    'x-oss-forbid-overwrite': 'true',
  };

  let mimetype = request.file.originalname.substring(request.file.originalname.lastIndexOf(".") + 1);
  // const time:number = Date.parse(new Date().toString()) / 1000
  const time: number = Math.floor(new Date().getTime());
  let imageName = upload_imageName + time;
  async function put () {
    try {
      // 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
      // 如果本地文件的完整路径中未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
      const result = await client.put(`${imageName}.${mimetype}`, path.normalize(request.file.path)
        // 自定义headers
        , { headers }
      );

      // 获取HTTPS链接
      const httpsUrl = `https://qiyat.oss-cn-beijing.aliyuncs.com/${result.name}`;
      result.url = httpsUrl;

      // if (result.res.status == 200) { }

      response.send(result)
    } catch (error) {
      console.log("error: ", error);
      next(error);
    }
  }

  await put();

  if (1 == 1) return





  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/goods/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })
    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const goodsData = await updateShop(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(goodsData)
  } catch (error) {
    next(error);
  }
}

/**
 * 删除文件
 */
export const delUploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件名
  let { fileName } = request.body;
  let { postId } = request.body;

  const client = new OSS({
    region: 'oss-cn-beijing', 
    accessKeyId: 'LTAI5tNGq1paq6keMtntM2CH', 
    accessKeySecret: 'MenjKujH7u7wpfVZ6pJqM4O5a7JevP',
    bucket: 'qiyat', 
  });

  async function deleteObject () {
    try {
      const result = await client.delete(`${fileName}`);
      if (postId && postId>0) {
        let image_url = null;
        let moviceModal: any = { image_url };
        await updateHouse(moviceModal, parseInt(postId, 10));
      }
      
      response.send(result);
    } catch (error) {
      console.log(error);
    }
  }

  deleteObject();

}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 要提供的图像尺寸
    const { size } = request.query;

    // 文件名与目录
    let filename = file[0].filename;
    let root = 'uploads/goods/resized';
    let resized = 'resized';

    if (size) {
      // 可用的图像尺寸
      const imageSize = ['lerge', 'medium', 'thumbnail'];

      // 检查文件尺寸是否可用
      if (!imageSize.some(item => item == size)) {
        throw new Error('FILE_NOT_FOUND');
      }

      // 检查文件是否存在
      const fileExist = fs.existsSync(
        path.join(root, resized, `${filename}-${size}`),
      )

      // 设备文件名与目录
      if (fileExist) {
        filename = `${filename}-${size}`;
        root = path.join(root, resized);
      }
    }

    // 做出响应
    response.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file[0].mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })

}
